import React, { useState, createContext, useContext } from 'react'
import { createRoot } from 'react-dom/client'
import MediaPreview from '@/components/MediaPreview'

// 类型定义
interface MediaInfo {
  type: 'video' | 'audio' | 'image'
  url: string
  title?: string
}

interface PreviewContextType {
  preview: (mediaInfo: MediaInfo) => void
}

// 创建 Context
const PreviewContext = createContext<PreviewContextType | null>(null)

// Provider 组件
export function MediaPreviewProvider({ children }: { children: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false)
  const [currentMedia, setCurrentMedia] = useState<MediaInfo | null>(null)

  const preview = (mediaInfo: MediaInfo) => {
    setCurrentMedia(mediaInfo)
    setIsOpen(true)
  }

  return (
    <PreviewContext.Provider value={{ preview }}>
      {children}
      {currentMedia && (
        <MediaPreview
          open={isOpen}
          onClose={() => setIsOpen(false)}
          {...currentMedia}
        />
      )}
    </PreviewContext.Provider>
  )
}

// Hook
export function useMediaPreview() {
  const context = useContext(PreviewContext)

  if (!context) {
    throw new Error('useMediaPreview must be used within a MediaPreviewProvider')
  }

  return context.preview
}

// 独立的预览方法（不依赖 Provider）
let container: HTMLDivElement | null = null
let root: any | null = null

export const preview = (mediaInfo: MediaInfo) => {
  if (!container) {
    container = document.createElement('div')
    document.body.appendChild(container)
    root = createRoot(container)
  }

  const handleClose = () => {
    root?.render(null)
  }

  root?.render(<MediaPreview open={true} onClose={handleClose} {...mediaInfo} />)
}

// // 使用示例:
// const ExampleComponent = () => {
//   // 方式1：使用 Hook（需要 Provider）
//   const preview = useMediaPreview()

//   // 方式2：直接使用导出的方法（不需要 Provider）
//   const handlePreview = () => {
//     preview({
//       type: 'video',
//       url: 'https://example.com/video.mp4',
//       title: '示例视频',
//     })
//   }

//   return <button onClick={handlePreview}>预览视频</button>
// }
